// 函数组件
import React, { useState, useEffect, useContext } from 'react';
import '../../css/public.less'
import './css/OrderExchangeCss/OrderExchange.less'
import { Input, ConfigProvider, DatePicker, Space, message, Tag, Button, Table, Modal, DatePickerProps } from 'antd';
import type { ColumnsType } from 'antd/es/table'
import zh_CN from 'antd/es/locale/zh_CN';
import { useNavigate } from 'react-router-dom'
import { getRefundAll, selectCondition } from '../../../api/OrderApi'

function OrderExchange() {
    const navigate = useNavigate()

    // const [isModalOpen, setIsModalOpen] = useState(false); // 对话框是否打开
    const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
    const [loading, setLoading] = useState(false);
    const [Select, SetSelect] = useState('all')  //选择的某个状态的订单数据
    const [order, setInputOrder] = useState<string>('')  //获取订单号输入框的值
    const [user, setInputUser] = useState<string>('')  //获取手机号/用户昵称号输入框的值
    const [date, setInputDate] = useState<string | null>()  //获取订单号输入框的值
    const [pageCount, setPageCount] = useState<number>()  //订单条数
    const [selectState, setSelectState] = useState<number>(4) //当前在哪个状态下
    const [pageSize, setPageSize] = useState<number>(2) //每页条数
    const [currentPage, setCurrentPage] = useState<number>(1) //当前第几页
    const [data, setData] = useState<DataType[]>([])    //所有数据

    const [Count1, setCount1] = useState<number>();
    const [Count2, setCount2] = useState<number>();
    const [Count3, setCount3] = useState<number>();
    const [Count, setCount] = useState<number>();
    // const [data, setData] = useState<DataType[]>([
    //     {
    //         key: 1,
    //         id: 1,
    //         order: `1001`,
    //         date: `2023-2-27`,
    //         user: 123,
    //         money: 100,
    //         type: '退货',
    //         payment: `待处理`,
    //         root: `2023-2-27`,
    //     },
    //     {
    //         key: 2,
    //         id: 2,
    //         order: `1002`,
    //         date: `2023-2-27`,
    //         user: 123,
    //         money: 100,
    //         type: '换货',
    //         payment: `已处理`,
    //         root: `2023-2-27`,
    //     },
    //     {
    //         key: 3,
    //         id: 3,
    //         order: `1003`,
    //         date: `2023-2-27`,
    //         user: 123,
    //         money: 100,
    //         type: '退货',
    //         payment: `已拒绝`,
    //         root: `2023-2-27`,
    //     },
    //     {
    //         key: 4,
    //         id: 4,
    //         order: `1003`,
    //         date: `2023-2-27`,
    //         user: 123,
    //         money: 100,
    //         type: '退货',
    //         payment: `已拒绝`,
    //         root: `2023-2-27`,
    //     },
    //     {
    //         key: 5,
    //         id: 5,
    //         order: `1003`,
    //         date: `2023-2-27`,
    //         user: 123,
    //         money: 100,
    //         type: '退货',
    //         payment: `已拒绝`,
    //         root: `2023-2-27`,
    //     },
    // ]);

    //日期选择框操作
    const { RangePicker } = DatePicker;
    // console.log('DatePicker',DatePicker);



    interface DataType {
        key: React.Key;
        marketState: number;//申请状态
        orderId: number;
        marketTime: string;//申请时间
        marketNum: number;//申请编号
        orderTotal: number;
        handlingTime: string; //处理时间        
        salesType: number;
    }

    const columns: ColumnsType<DataType> = [
        {
            title: '序号',
            dataIndex: 'orderId',
        },
        {
            title: '订单编号',
            dataIndex: 'marketNum',
        },
        {
            title: '申请时间',
            dataIndex: 'marketTime',
        },
        // {
        //     title: '用户账号',
        //     dataIndex: 'user',
        // },
        {
            title: '金额',
            dataIndex: 'orderTotal',
            render: (_, record) => (
                <Space size="middle">
                    <Button type="link">{record.orderTotal}</Button>
                </Space >
            ),
        },
        {
            title: '类型',
            dataIndex: 'salesType',
            render: (_, record) => (
                record.salesType == 1 ? <Tag color="#f50">退货</Tag> : <Tag color="#87d068">退款</Tag>
                // </Tag>
            ),
        },
        {
            title: '申请状态',
            dataIndex: 'marketState',
            render: (_, record) => (

                record.marketState == 1 ? <Tag color="#f50">待处理</Tag> : record.marketState == 2 ? <Tag color="#2db7f5">已处理</Tag> : <Tag color="#87d068">已拒绝</Tag>
                // </Tag>
            ),
        },
        {
            title: '处理时间',
            dataIndex: 'handlingTime',
        },
        {
            title: '操作',
            dataIndex: 'operation',
            render: (_, record) => (
                <div className='state-button'>
                    <button onClick={() => { examineBtn(record) }} className='one'> 查看详情</button>
                </div>
            )
        },
    ];

    const start = () => {
        setLoading(true);
        // ajax request after empty completing
        setTimeout(() => {
            setSelectedRowKeys([]);
            setLoading(false);
        }, 1000);
    };

    // const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    //     console.log('selectedRowKeys changed: ', newSelectedRowKeys);
    //     setSelectedRowKeys(newSelectedRowKeys);
    // };

    // const rowSelection = {
    //     selectedRowKeys,
    //     onChange: onSelectChange,
    // };
    // const hasSelected = selectedRowKeys.length > 0;



    useEffect(() => {
        console.log('OrderExchange组件来咯')
        getAll()
    }, [])

    // 获取所有退款数据的函数
    const getAll = () => {
        console.log('执行了这个函数');
        getRefundAll({
            salesType: selectState,
            pageNum: currentPage,
            size: pageSize
        }).then(res => {
            console.log('退换货数据res', res);
            setData(res.data.aftermarketDtos)
            setPageCount(res.data.count)

            const { AfterCount1, AfterCount2, AfterCount3, allAfterCount } = res.data.afterCountMap
            console.log('AfterCount2', AfterCount2);

            setCount1(AfterCount1)
            setCount2(AfterCount2)
            setCount3(AfterCount3)
            setCount(allAfterCount)

        }).catch(err => {
            console.log('err报错了', err);

        })
    }

    //页码或 pageSize 改变的回调，参数是改变后的页码及每页条数
    const pageChange = (page: number, pageSize: number) => {
        console.log('page pageSize', page, pageSize);
        // 发请求
        setPageSize(pageSize)
        setCurrentPage(page)
        if (selectState == 4) {
            getRefundAll({
                // state:selectState,
                salesType: selectState,//(查询退款),
                pageNum: page,
                size: pageSize,
            }).then(res => {
                setData(res.data.aftermarketDtos)
                setPageCount(res.data.count)
                // 设置当前页和每页条数
                setPageSize(pageSize)
                setCurrentPage(page)
                console.log('res111', res);

            }).catch(err => {
                console.log('err222', err);

            })
        } else {
            selectCondition({
                marketState: selectState,
                size: pageSize,
                salesType: selectState,
                page: currentPage
            }).then(res => {
                console.log('res', res);
                // message.success(res.msg);
                setPageCount(res.data.count)
                setData(res.data.aftermarketDtos)
            }).catch(err => {
                console.log('err', err);
            })
        }
        if (selectState == 4) {
            getRefundAll({
                // state:selectState,
                salesType: selectState,//(查询退款),
                pageNum: page,
                size: pageSize,
            }).then(res => {
                setData(res.data.aftermarketDtos)
                setPageCount(res.data.count)
                // 设置当前页和每页条数
                setPageSize(pageSize)
                setCurrentPage(page)
                console.log('res111', res);

            }).catch(err => {
                console.log('err222', err);

            })
        } else {
            selectCondition({
                marketState: selectState,
                size: pageSize,
                salesType: selectState,
                page: currentPage
            }).then(res => {
                console.log('res', res);
                // message.success(res.msg);
                setPageCount(res.data.count)
                setData(res.data.aftermarketDtos)
            }).catch(err => {
                console.log('err', err);
            })
        }
        // getRefundAll({
        //     // state:selectState,
        //     salesType: 1,//(查询退款),
        //     pageNum: page,
        //     size: pageSize,
        // }).then(res => {
        //     setData(res.data.aftermarketDtos)
        //     setPageCount(res.data.count)
        //     // 设置当前页和每页条数
        //     setPageSize(pageSize)
        //     setCurrentPage(page)
        // }).catch(err => {
        //     console.log('err错误', err);

        // })
    }

    // 点击头部按钮选择显示所有退款、待处理、已处理、已拒绝
    const onClickBtn = (type: string, numstate: number) => {
        SetSelect(type)
        console.log('我来咯，请响应', type);
        // getRefundAll({
        //     // salesType: 1,
        //     state:Select,
        //     pageNum: currentPage,
        //     size: pageSize
        // }).then(res => {
        //     console.log('所有退款res', res);
        //     setData(res.data.aftermarketDtos)
        //     setPageCount(res.data.count)

        // }).catch(err => {
        //     console.log('err报错了', err);

        // })
        if (selectState == 4) {
            getRefundAll({
                salesType: selectState,//(查询所有),
                pageNum: currentPage,
                size: pageSize
            }).then(res => {
                console.log('所有退款res', res);
                setData(res.data.aftermarketDtos)
                setPageCount(res.data.count)
                const { allAfterCount } = res.data.afterCountMap
                setCount(allAfterCount)
            }).catch(err => {
                console.log('err565665', err);
            })
        } else if (selectState == 1) {
            selectCondition({
                marketState: selectState,
                size: pageSize,
                salesType: 3,
                page: currentPage
            }).then(res => {
                console.log('res', res);
                // message.success(res.msg);
                setPageCount(res.data.count)
                setData(res.data.aftermarketDtos)

                //
                // setAfterCount1(res.data.count)
            }).catch(err => {
                console.log('err', err);
            })
        } else {
            selectCondition({
                marketState: numstate,
                size: pageSize,
                salesType: numstate,
                page: currentPage
            }).then(res => {
                console.log('res', res);
                // message.success(res.msg);
                setPageCount(res.data.count)
                setData(res.data.aftermarketDtos)

            }).catch(err => {
                console.log('err', err);
            })
        }

    }

    //点击获取查看详情
    const examineBtn = (record: DataType) => {
        console.log('打印v', record);
        //路由跳转，传输数据
        navigate('/home/order/RefundDetails', { state: record.orderId })

    }



    //筛选
    const handleChange = (e: any) => {
        setInputOrder(e.target.value);
    }
    const handleChange1 = (e: any) => {
        setInputUser(e.target.value);
    }
    const handleChange2: DatePickerProps['onChange'] = (date, dateString) => {
        let dateMsg = dateString
        setInputDate(dateMsg);
        console.log('date', dateMsg);

    }
    const filterInput = () => {

        selectCondition({
            marketTime: date, //创建时间 
            orderId: order,
            marketState: selectState,
            salesType: 1,
            page: currentPage,//当前页
            size: pageSize,//每页多少条
        }).then(res => {
            console.log('根据条件查询订单结果res', res.data.msg);
            // if(res.code==200){
            console.log(111111111);
            setPageCount(res.data.count)
            setData(res.data.aftermarketDtos);
            message.success('查询订单成功')
            // if (res.data.allOrderDtos.length > 0) {
            //     // 查询出有数据
            //     message.success('查询订单成功')
            // } else {
            //     // 没有数据
            //     // message.info(res.msg)
            //     message.info('没有数据')

            // }
            // }

        }).catch(err => {
            console.log('err333', err);
            message.error('服务器错误')
        })

    }

    // 搜索重置
    const resetHandle = (event: any) => {
        // 阻止默认事件
        event.preventDefault()
        console.log('重置');
        // 清空搜索框
        setInputOrder('');
        setInputUser('');
        setInputDate('');
        // 重新获取数据
        getAll()
    }




    // //点击删除
    // const delBtn = (v: number) => {
    //     console.log('点击删除了', v);
    //     let delList = data.filter(item => item.key !== v)
    //     setData(delList)
    // }


    return (
        <div className='OrderExchange'>
            {/* 头部 */}
            <div className='page-top'>
                {/* 左边标题 */}
                <div className='page-title'>
                    <p>退换货申请</p>
                </div>
            </div>
            <div className='page-div-top'>
                <div className={Select == 'all' ? 'selectBtn' : ''} onClick={() => onClickBtn('all', 4)}>全部申请( <p>{Count}</p> )</div>
                <div className={Select == 'penDing' ? 'selectBtn' : ''} onClick={() => onClickBtn('penDing', 1)}>待处理( <p>{Count2}</p> )</div>
                <div className={Select == 'proCessed' ? 'selectBtn' : ''} onClick={() => onClickBtn('proCessed', 2)}>已处理( <p>{Count3}</p> )</div>
                <div className={Select == 'rejecTed' ? 'selectBtn' : ''} onClick={() => onClickBtn('rejecTed', 3)}>已拒绝( <p>{Count1}</p> )</div>
            </div>
            {/* 内容区 */}
            <div className='page-context' style={{ paddingTop: '10px' }}>
                {/* 查询部分 */}
                <div className='banner-search'>
                    <div className='banner-query'>
                        <p>筛选查询</p>
                    </div>
                    <div className='banner-input'>
                        <div className='banner-input-div'>关键词<Input value={order} onChange={handleChange} placeholder="订单号/商品货号" /></div>
                        <div>收货人<Input placeholder="手机号/用户昵称" value={user} onChange={handleChange1} /></div>
                        <div className='banner-input-date'>申请时间<DatePicker onChange={handleChange2} renderExtraFooter={() => 'extra footer'} showTime placeholder="请选择时间" style={{ width: '250px', height: '35px', marginLeft: '18px' }} /></div>
                    </div>
                    <div className='banner-button'>
                        <Button type="primary" className='reset' onClick={resetHandle}>重置</Button>
                        <Button type="primary" className='filter' onClick={filterInput}>筛选</Button>
                    </div>

                </div>
                {/* 数据表格部分 */}
                <div className='data-list'>
                    <div className='data-list-div'><p>数据列表</p>
                        <div className='data-list-context'>
                            <div style={{ marginBottom: 2 }}>
                                <span style={{ marginLeft: 8 }}>
                                    {/* {hasSelected ? `${selectedRowKeys.length}` : ''} */}
                                </span>
                            </div>
                            <ConfigProvider locale={zh_CN}>
                                <Table
                                    // rowSelection={rowSelection}
                                    rowKey={item => item.orderId}
                                    columns={columns}
                                    dataSource={data}
                                    pagination={
                                        {
                                            position: ['bottomCenter'],
                                            total: pageCount,
                                            defaultPageSize: pageSize,
                                            defaultCurrent: currentPage,
                                            pageSizeOptions: [2,4, 8, 12],
                                            showQuickJumper: true,
                                            showSizeChanger: true,
                                            onChange: pageChange,
                                            showTotal: (total: number) => `共有 ${total} 条数据`
                                        }
                                    }
                                />
                            </ConfigProvider>
                        </div>
                    </div>
                </div>
            </div>

            {/* <Modal title="删除" open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
                <p>确定将该学生删除吗？</p>
            </Modal> */}

        </div>
    )
}

export default OrderExchange